package com.yk.i_wms.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yk.i_wms.common.model.PageResult;
import com.yk.i_wms.common.model.Result;
import com.yk.i_wms.dto.SmsCheckDocDTO;
import com.yk.i_wms.model.SmsCheckDoc;
import com.yk.i_wms.model.SmsCheckDocDetail;
import com.yk.i_wms.model.SmsCheckDocRecord;
import com.yk.i_wms.service.ISmsCheckDocDetailService;
import com.yk.i_wms.service.ISmsCheckDocRecordService;
import com.yk.i_wms.service.ISmsCheckDocService;
import com.yk.i_wms.util.EasyPoiExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 盘点单
 *
 * @author hbq
 * @date 2021-04-14 19:17:53
 */
@Slf4j
@CrossOrigin
@RestController
@Api(tags = "盘点单")
@RequestMapping("sms")
public class SmsCheckDocController {
    @Autowired
    private ISmsCheckDocService smsCheckDocService;
    @Autowired
    private ISmsCheckDocDetailService smsCheckDocDetailService;
    @Autowired
    private ISmsCheckDocRecordService smsCheckDocRecordService;
    /**
     * 列表
     */
    @ApiOperation(value = "查询列表")
    @PostMapping("/smsCheckDoc/list")
    public Result<PageResult> list(@RequestBody Map<String, Object> params) {
        Page<Map> list= smsCheckDocService.findList(params);
        return Result.succeed(PageResult.restPage(list),"查询成功");
    }

    /**
     * 扫码盘点
     */
    @ApiOperation(value = "扫码盘点")
    @PostMapping("/smsCheckDoc/scanSN")
    public Result scanSN(@RequestBody Map<String, Object> params) {
        return smsCheckDocService.scanSN(params);
    }

    /**
     * 查询
     */
    @ApiOperation(value = "查询")
    @PostMapping("/smsCheckDoc/sel/{id}")
    public Result findUserById(@PathVariable Long id) {
        SmsCheckDoc model = smsCheckDocService.getById(id);
        return Result.succeed(model, "查询成功");
    }

    /**
     * 新增or更新
     */
    @ApiOperation(value = "新增or更新")
    @PostMapping("/smsCheckDoc/save")
    public Result save(@RequestBody SmsCheckDoc smsCheckDoc) {
        smsCheckDocService.saveOrUpdate(smsCheckDoc);
        return Result.succeed("保存成功");
    }

    /**
     * 新增or更新(包含详情)
     */
    @ApiOperation(value = "新增or更新(包含详情)")
    @PostMapping("/smsCheckDoc/saveAll")
    public Result saveAll(@RequestBody SmsCheckDocDTO smsCheckDocDTO) {
        return smsCheckDocService.saveAll(smsCheckDocDTO);
    }

    /**
     * 根据单号查详情
     */
    @ApiOperation(value = "根据单号查详情")
    @PostMapping("/smsCheckDoc/selAllByDocNo")
    public Result selAllByDocNo(@RequestBody Map<String, Object> params) {
        String docNo = MapUtil.getStr(params, "docNo");
        SmsCheckDoc checkDoc = smsCheckDocService.getOne(new LambdaQueryWrapper<SmsCheckDoc>()
                .eq(SmsCheckDoc::getDocNo, docNo));
        Map<String, Object> resultMap = BeanUtil.beanToMap(checkDoc);
        List<SmsCheckDocDetail> checkDocDetailMaps = smsCheckDocDetailService.list(new LambdaQueryWrapper<SmsCheckDocDetail>().eq(SmsCheckDocDetail::getDocNo, docNo));
        List<Map<String, Object>> checkDocDetails=new ArrayList<>();
        for (SmsCheckDocDetail checkDocDetail : checkDocDetailMaps) {
            Map<String, Object> checkDocDetailMap = BeanUtil.beanToMap(checkDocDetail);
            Long id = checkDocDetail.getId();
            int totalCount = smsCheckDocRecordService.count(new LambdaQueryWrapper<SmsCheckDocRecord>()
                    .eq(SmsCheckDocRecord::getDdId, id)
            );
            int checkCount = smsCheckDocRecordService.count(new LambdaQueryWrapper<SmsCheckDocRecord>()
                    .eq(SmsCheckDocRecord::getDdId, id)
                    .eq(SmsCheckDocRecord::getState,2)
            );
            String checkState="";
            String checkResult="";
            if (checkCount==0){
                checkState="未开始";
                checkResult="未开始";
            } else if (checkCount==totalCount){
                checkState="盘点结束";
                long remainCount = checkDocDetail.getCheckQty() - checkDocDetail.getCheckEndQty();
                if (remainCount>0){
                    checkResult="盘亏";
                }
                if (remainCount==0){
                    checkResult="正常";
                }
                if (remainCount<0){
                    checkResult="盘盈";
                }
            }else {
                checkState="盘点中";
                checkResult="盘点中";
            }
            checkDocDetailMap.put("checkState",checkState);
            checkDocDetailMap.put("checkResult",checkResult);
            checkDocDetails.add(checkDocDetailMap);
        }
        resultMap.put("checkDocDetails",checkDocDetails);
        return Result.succeed(resultMap, "查询成功");
    }

    /**
     * 根据详情id查sn记录
     */
    @ApiOperation(value = "根据详情id查sn记录")
    @PostMapping("/smsCheckDoc/selRecordByDdId")
    public Result selRecordByDdid(@RequestBody Map<String, Object> params) {
        String ddId = MapUtil.getStr(params, "ddId");
        List<SmsCheckDocRecord> smsCheckDocRecords = smsCheckDocRecordService.list(new LambdaQueryWrapper<SmsCheckDocRecord>()
                .eq(SmsCheckDocRecord::getDdId, ddId));
        return Result.succeed(smsCheckDocRecords, "查询成功");
    }
    /**
     * 批量新增or更新
     */
    @ApiOperation(value = "批量新增or更新")
    @PostMapping("/smsCheckDoc/saveBatch")
    public Result saveBatch(@RequestBody Map<String,List<SmsCheckDoc>> map) {
        List<SmsCheckDoc> models = map.get("models");
        smsCheckDocService.saveOrUpdateBatch(models);
        return Result.succeed("保存成功");
    }

    /**
     * 删除
     */
    @ApiOperation(value = "批量删除")
    @PostMapping("/smsCheckDoc/del")
    public Result delete(@RequestBody Map<String,List<Long>> map) {
        return smsCheckDocService.delete(map);
    }
    /**
     * 关结
     */
    @ApiOperation(value = "关结")
    @PostMapping("/smsCheckDoc/close")
    public Result close(@RequestBody SmsCheckDoc smsCheckDoc) {
        return smsCheckDocService.close(smsCheckDoc);
    }

    /**
     * 导入
     */
    @ApiOperation(value = "导入")
    @PostMapping("/smsCheckDoc/leadIn")
    public  Result leadIn(MultipartFile excel) throws Exception {
        int rowNum = 0;
        if (!excel.isEmpty()) {
            List<SmsCheckDoc> list = EasyPoiExcelUtil.importExcel(excel, 1, 1, SmsCheckDoc.class);
            rowNum = list.size();
            if (rowNum > 0) {
                list.forEach(u -> {
                        smsCheckDocService.save(u);
                });
                return Result.succeed("成功导入信息"+rowNum+"行数据");
            }
        }
        return Result.failed("导入失败");
    }
    
    /**
     * 导出（传入ids数组，选择指定id）
     */
    @ApiOperation(value = "导出（传入ids数组，选择指定id）")
    @PostMapping("/smsCheckDoc/leadOut")
    public void leadOut(@RequestBody Map<String,List<Long>> map,HttpServletResponse response) throws IOException {
        List<Long> ids = map.get("ids");
        List<SmsCheckDoc> smsCheckDocList = ids==null||ids.isEmpty()? smsCheckDocService.list():(List)smsCheckDocService.listByIds(ids);
        //导出操作
        EasyPoiExcelUtil.exportExcel(smsCheckDocList, "盘点单导出", "盘点单导出", SmsCheckDoc.class, "smsCheckDoc.xls", response);
    }
}
